<?php

namespace backend\controllers;

use common\logic\UserLogic;
use common\models\ReturnLogModel;
use common\models\UserModel;
use Yii;
use common\models\ReportModel;
use backend\models\SearchReportModel;
use backend\controllers\BaseController;
use yii\web\NotFoundHttpException;
use yii\filters\VerbFilter;
use yii\web\User;

/**
 * ReportController implements the CRUD actions for ReportModel model.
 */
class ReportController extends BaseController
{


    /**
     * Lists all ReportModel models.
     *
     * @return mixed
     */
    public function actionIndex($referee = 0)
    {
        $searchModel = new SearchReportModel();
        $dataProvider = $searchModel->search(Yii::$app->request->queryParams, $referee);

        return $this->render('index', [
            'searchModel' => $searchModel,
            'dataProvider' => $dataProvider,
        ]);
    }

    public function actionSign($id)
    {
        $model = $this->findModel($id);
        $model->sign_time = $model->return_time = $model->sign_amount = $model->return_amount = $model->sign_house = '';
        if (Yii::$app->request->isPost) {
            $data = Yii::$app->request->post();
            if ($data['ReportModel']['sign'] == 2) {
                $model->sign = 2;
                $model->return_time = 0;
                $model->return_amount = 0;
                $model->sign_amount = 0;
                $model->sign_time = 0;
                $model->sign_house = '';
                $model->save();

                return $this->redirect(['index', 'id' => $model->id]);
            } else {
                $data['ReportModel']['return_time'] = strtotime($data['ReportModel']['return_time']);
                $data['ReportModel']['sign_time'] = strtotime($data['ReportModel']['sign_time']);
            }
            if ($model->load($data) && $model->save()) {


                if ($model->sign == 1) {
                    $referee = 0;

                    $user = UserModel::findOne(['id' => $model->uid]);

                    if (in_array($user->role, [UserModel::ROLE_PARTNER,0])) {
                        if ($model->status == '自看') {
                            $referee = $user->id;
                        }

                        $parent_code = $user->parent_code . $user->id;
                    } else {
                        $parent_code = $user->parent_code;
                    }

                    $parent_code = explode('_', $parent_code);
                    $parent_code = array_filter($parent_code);
                    $settings = [5, 10, 20];

                    $count = count($parent_code) - 1;
                    $count = $count < 0 ? 0 : $count;
                    foreach ($settings as $k => $v) {
                        if ($k > $count) {
                            $settings[$count] += $v;
                            if($count>0) {
                                unset($settings[$k]);
                            }
                        }
                    }


                    $returnAmount = [];
                    foreach ($parent_code as $k => $uid) {
                        $child_id = empty($parent_code[$k + 1]) ? 0 : $parent_code[$k + 1];
                        $ext = 0;

                        //自己推荐自己，再加50个点
                        if ($referee == $model->uid && $referee == $uid) {
                            $ext = 50;
                        }

                        $returnAmount[] = [
                            'uid' => $uid,
                            'amount' => sprintf('%.2f', $model->return_amount * 2 * ($settings[$k] + $ext) / 100),
                            'report_id' => $model->id,
                            'buyer' => $model->uid,
                            'child_id' => $child_id,
                            'create_at' => time()];
                    }

//                    //自己平台
//                    if ($user->source_id == 1) {
//                        unset($returnAmount[0]);
//                    }
                    if (!empty($returnAmount)) {
                        foreach ($returnAmount as $item) {
                            $log = new ReturnLogModel();
                            $log->setAttributes($item);
                            $log->save();
                        }
                    }


                }


                return $this->redirect(['index', 'id' => $model->id]);
            }
        }

        return $this->render('sign', [
            'model' => $model,
        ]);
    }


    /**
     * Displays a single ReportModel model.
     *
     * @param integer $id
     *
     * @return mixed
     */
    public function actionView($id)
    {
        $model = ReportModel::find()->joinWith('house')->alias('r')->where(['r.id' => $id])->one();
        if (empty($model)) {
            throw new NotFoundHttpException('The requested page does not exist.');
        }

        return $this->render('view', [
            'model' => $model,
        ]);
    }

    /**
     * Creates a new ReportModel model.
     * If creation is successful, the browser will be redirected to the 'view' page.
     *
     * @return mixed
     */
    public function actionCreate()
    {
        $model = new ReportModel();

        if ($model->load(Yii::$app->request->post()) && $model->save()) {
            return $this->redirect(['view', 'id' => $model->id]);
        } else {
            return $this->render('create', [
                'model' => $model,
            ]);
        }
    }


    /**
     * Updates an existing ReportModel model.
     * If update is successful, the browser will be redirected to the 'view' page.
     *
     * @param integer $id
     *
     * @return mixed
     */
    public function actionUpdate($id)
    {
        $model = $this->findModel($id);

        if ($model->load(Yii::$app->request->post()) && $model->save()) {
            return $this->redirect(['view', 'id' => $model->id]);
        } else {
            return $this->render('update', [
                'model' => $model,
            ]);
        }
    }

    /**
     * Deletes an existing ReportModel model.
     * If deletion is successful, the browser will be redirected to the 'index' page.
     *
     * @param integer $id
     *
     * @return mixed
     */
    public function actionDelete($id)
    {
        $this->findModel($id)->delete();

        return $this->redirect(['index']);
    }

    /**
     * Finds the ReportModel model based on its primary key value.
     * If the model is not found, a 404 HTTP exception will be thrown.
     *
     * @param integer $id
     *
     * @return ReportModel the loaded model
     * @throws NotFoundHttpException if the model cannot be found
     */
    protected function findModel($id)
    {
        if (($model = ReportModel::findOne($id)) !== null) {
            return $model;
        } else {
            throw new NotFoundHttpException('The requested page does not exist.');
        }
    }
}
